<?php

namespace App\Http\Controllers;

use App\Http\Service\UserService;
use App\Http\Service\Baoliao\BaoliaoService;
use App\Http\Service\Baoliao\Baoliao3Service;
use App\Http\Service\Baoliao\BaoliaolikeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Config;
use App\Http\Service\ViewcountService;
use Illuminate\Support\Facades\DB;
use App\Http\Service\Baoliao\BaoliaoDetailfanganService;

class BaoliaoController extends BaseController
{
    public $URL_MAP;
    private $getRules=[
            'unique_id'=> 'required',
            'people_id'=> 'required',
        ];
    private  $getRulesMessage=[
            'unique_id.required'=> '唯一标识【unique_id】不能为空',
            'people_id.required'=> '用户id【people_id】不能为空',
        ];
    public $repository;
    public function __construct(BaoliaoService $repository, BaoliaolikeService $baoliaolikeService,UserService $userService,ViewcountService $historyservice,Baoliao3Service $baoliao3Service,BaoliaoDetailfanganService $baoliaoDetailfanganService)
    {
        $this->URL_MAP=config('myurl.URL_MAP');

        parent::__construct();
        $this->repository = $repository;
        $this->baoliaolikeService = $baoliaolikeService;
        $this->userService=$userService;
        $this->historyservice = $historyservice;
        $this->baoliao3Service=$baoliao3Service;
        $this->baoliaoDetailfanganService=$baoliaoDetailfanganService;
    }

    //爆料列表
    public function getList(Request $request)
    {
        //item_type=1 爆料项目 2 心动日记项目
        $data=[
            'unit_type'=>$request->input("unit_type"),
            'content'=>$request->input("content"),
            'people_id'=>$request->input("people_id"),
            'type'=>$request->input("type"),
            'item_type'=>$request->input("item_type"),
        ];

        $this->success($this->repository->getList($request,$data));
        
    }
    //爆料详情
    public function dataDetail(Request $request)
    {
        $data=[
            'unique_id'=>$request->input("unique_id"),
            'people_id'=>$request->input("people_id"),
        ];

        $this->checkrule($data,$this->getRules,$this->getRulesMessage);

        //添加历史记录
        
        $yunique_id=explode(",",$data['unique_id']);
        $data['unique_id']=$yunique_id['1'];
        $data['table_type']=$yunique_id['0'];
        //dd($yunique_id);
        if($data['table_type']=='list'){
            $first=DB::table("vw_baoliao_post_list_all")->where(['unique_id'=>$data['unique_id']])->first();
        }else{
            //dd($data['unique_id']);

            $first=DB::table("baoliao_post_back")->where(['unique_id'=>$data['unique_id']])->first();
            if($first){
                $first=(object)$first;
            }else{
                $first=[];
            }

        }
        //dd($first);
        if(empty($first)){
            $this->error("帖子不存在");
        }
        $hdata=$data;
        $hdata['type']='2';
        $hdata['type_son']='6';
        //dd($first);
        $hdata['title']=$first->title;
        $hdata['avatar']=$first->avatar;
        $hdata['user_id']=$first->user_id;
        $hdata['cover']=$first->cover;
        $hdata['nickname']=$first->nickname;
        $hdata['unit_price']=$first->unit_price;
        $hdata['commission_amount']=$first->commission_amount;
        $hdata['publish_time']=$first->publish_time;
        //unset($hdata['table_type']);

        $this->historyservice->addDate($request,$hdata);


        $data['item_type']=$request->input("item_type");


        $this->success($this->repository->dataDetail($request,$data));
        
    }
    //爆料详情-方案
    public function dataDetailfangan(Request $request)
    {
        $data=[
            'product_id'=>$request->input("unique_id"),
            'people_id'=>$request->input("people_id"),
            'platform_name'=>$request->input("platform_name"),
            'id'=>$request->input("id"),
            'item_type'=>$request->input("item_type"),
        ];
        //dd($data);
        #判断商品id是否重复
        $product_id=$data['product_id'];
        $platform_name=$data['platform_name'];
        if($product_id){
            $ar=platform_name_product_id($platform_name,$product_id);
            //dd($ar);
            if(is_array($ar)){
                $product_id=$ar['1'];
               // dd($product_id);
            }
        }
        $data['product_id']=$product_id;
        $this->success($this->baoliaoDetailfanganService->dataDetailfangan($request,$data));
        
    }
    //方案-详情
    public function baoliaoDetailfangandefault(Request $request)
    {
        $data=[
            'class'=>$request->input("class"),
            'unique_id'=>$request->input("unique_id"),
            'people_id'=>$request->input("people_id"),
            'item_type'=>$request->input("item_type"),
        ];
        $this->success($this->repository->baoliaoDetailfangandefault($request,$data));
    }
    //爆料信息上传-机器人-不能删除
    public function perfectInfo3(Request $request)
    {
        $type=$request->json("type");
        if(empty($type)){
            $type=3;
        }
        #用户id
        $user_id=$request->json("user_id");
        $avatar="";
        $nickname="";
        if(!empty($user_id) && $user_id>=1000){
           $user_info=$this->userService->update_user($user_id);
           $nickname=$user_info['nickname'];
           $avatar=$user_info['avatar'];
           
        }
        if(empty($user_id)){
            $this->error("用户Id不能为空");
        }

        $purchase=[];
        $purchase_steps=[];
        $purchase_youhuiquan=$request->json("purchase_youhuiquan");
        $purchase_huodong=$request->json("purchase_huodong");
        $purchase_jiagou=$request->json("purchase_jiagou");
        $purchase_coudan=$request->json("purchase_coudan");

        if(!empty($purchase_youhuiquan)){
            $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
        }
        if(!empty($purchase_huodong)){
            $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
        }
        if(!empty($purchase_jiagou)){
            $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
        }
        if(!empty($purchase_coudan)){
            $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
        }
        //佣金比例
        $commission_rate=$request->json("commission_rate");
        if(empty($commission_rate)){
            $commission_rate=0.00;
        }
        $commission_rate=$commission_rate*100;
        //数量
        $quantity=$request->json("quantity",1);
        if(empty($quantity)){
            $quantity=1;
        }
        //单价
        $unit_price=$request->json("unit_price",0);
        if(empty($unit_price)){
            $unit_price=1;
        }
        //下单价
        $final_price=$unit_price*$quantity;
        //佣金金额
        $commission_amount=$request->json("commission_amount");
        //佣金总金额
        $commission_amount_total=$commission_amount*$quantity;

        $category_id=$request->json("category_id");
        $category_name=$request->json("category_name");
        $platform=$request->json("platform");
        //dd($platform);
        $productId=$request->json("product_id");
        //dd($productId);
        if($productId){
            $is_product=1;
        }
        //dd($platform);
        //测试京东
        //$platform='拼多多';
        //$productId='E9L2lYP4BSBHtvaxwfjfHwEH8luiqAiApA_JkqttchhD';

        if(!isset($this->URL_MAP[$platform])){
            $this->error("平台不存在,请联系管理员添加平台[{$platform}]");
        }
        $url=$this->URL_MAP[$platform];
        $product_list=[];
        if($url){
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform,$productId,$url);

            
            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }
        }



        $purchase_screenshots=[];
        $purchase_screenshots=$request->json("purchase_screenshots");
        $purchase_screenshots=array_filter($purchase_screenshots);
        $purchase_screenshots=array_unique($purchase_screenshots);
        //dd($purchase_screenshots);

        $image=[];
        $images=$request->json("images");
        $images=array_filter($images);
        $images=array_unique($images);

        $product_unique_id=$request->json("product_unique_id");
        if(empty($product_unique_id)&&$productId){
            $ar=explode('_',$productId);
            if(is_array($ar)){
                $product_unique_id=$ar['1'];
            }else{
                $product_unique_id=$productId;
            }

        }
        if(empty($product_unique_id)){
            $this->error("product_unique_id 不能为空");
        }
        $start_time=$request->json("start_time");
        $end_time=$request->json("end_time");

        #重新组装 unique_id
        $start_times=strtotime($start_time);
        $end_times=strtotime($end_time);
        if($end_times<$start_times){
            $this->error("结束时间不能大于开始时间");
        }
        if(empty($platform)){
            $this->error("平台[platform]不能为空");
        }
        $uniqid=uniqid() . '_' . time();
        #机器人上传数据唯一性判断  (后缀+平台)
        $unique_id="{$product_unique_id}_{$platform}";
        $unique_id=$uniqid;
        #判断帖子是否过期
        $is_expired = checkExpired($start_times, $end_times);
        //dd($is_expired);

        # title  值选替换星选
        $title=$request->json("title");
        $title=str_replace('值选', '星选', $title);
        #是否有官方补贴
        $is_subsidy=2;
        $is_subsidy_=$request->json("is_subsidy");
        if(!empty($is_subsidy_)){
            $is_subsidy=$is_subsidy_;
        }

        $subsidy_rate=$request->json("subsidy_rate");
        if(empty($subsidy_rate)){
            $subsidy_rate=0.00;
        }
        $subsidy_rate=$subsidy_rate*100;
        $data=[
            'unique_id'=>$unique_id,
            'is_product'=>$is_product,
            'purchase_steps'=>$purchase_steps,
            'title'=>$title,
            'platform_name'=>$platform,
            'start_time'=>$start_time,
            'article_title'=>$request->json("article_title"),
            'brand_name'=>$request->json("brand_name"),
            'end_time'=>$end_time,
            'content'=>$request->json("content"),
            'cover'=>$request->json("cover"),
            'product_id'=>$productId,
            'unit_price'=>$unit_price,
            'quantity'=>$quantity,
            'final_price'=>$final_price,
            'commission_amount_total'=>$commission_amount_total,
            'images'=>$images,
            'purchase_screenshots'=>$purchase_screenshots,
            'category_id'=>$category_id,
            'category_name'=>$category_name,
            'origain_price'=>$request->json("origain_price"),
            'commission_rate'=>$commission_rate,
            'commission_amount'=>$commission_amount,//佣金金额
            'shop_id'=>$request->json("shop_id"),
            'product_unique_id'=>$product_unique_id,
            'product_list'=>$product_list,
            'type'=>$type, //2用户添加数据  3.机器人推动数据
            'publish_time'=>date("Y-m-d H:i:s"),
            'is_expired'=>$is_expired,
            'user_id'=>$user_id,
            'avatar'=>$avatar,
            'nickname'=>$nickname,
            'subsidy_rate'=>$subsidy_rate,
            'subsidy_amount'=>$request->json("subsidy_amount"),
            'subsidy_name'=>$request->json("subsidy_name"),
            'is_subsidy'=>$is_subsidy,
            'jd_plus_commission_desc'=>$request->json("jd_plus_commission_desc"),

        ];
        

        if(empty($data['start_time'])){
            $this->error("开始时间不能为空");
        }
        if(empty($data['end_time'])){
            $this->error("结束时间不能为空");
        }

        
        if(!isStandardTime($data['start_time'])){
            $this->error("start_time  时间格式不标准【YYYY-MM-DD HH:MM:SS】");
        }
        if(!isStandardTime($data['end_time'])){
            $this->error("end_time  时间格式不标准【YYYY-MM-DD HH:MM:SS】");
        }
 


       // dd($data);

        $platform_name=$data['platform_name'];
        //活动，优惠，加购，凑单，下单
        $purchase_steps=$data['purchase_steps'];
        #组装数据
        foreach ($purchase_steps as $k=> &$v) {
            switch ($v['type']) {
                case '1':
                    $v['data-dimension122']="优惠券";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '2':
                    if(isset($v['link'])&&empty($v['link'])){
                        unset($purchase_steps[$k]);
                    }else{
                        $v['data-dimension122']="活动";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                    }
                    
                    break;
                case '3':
                    $v['data-dimension122']="加购";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '4':
                    $v['data-dimension122']="凑单";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                default:
            }


        }

        $link="";
        if(!empty($data['product_list'])){
            $link=$data['product_list'][0]['text'];
        }
        //dd($data['product_list']);
        //加购
        $purchase_steps[]=[
            "data-dimension122"=> "加购",
            "type"=>3,
            "tag_text"=> "下单{$quantity}件-{$data['title']}",
            "you_hui_tiao_zhuan_link_end"=> "",
            "huo_dong_time"=> null,
            "platform"=>$platform_name,
            "title"=> "加购",
            "description"=> "下单{$quantity}件-{$data['title']}",
            "link"=>$link,

        ];

        //下单
        if($quantity>1){

            $lastunitPrice = $unit_price-$commission_amount;
            //dd($commission_amount);
            //$shifu=$unit_price*$quantity;
            $lastunitPrice =_round($lastunitPrice);
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "title"=> "下单",
                "type"=> 5,
                "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                "link"=>'',
                "platform"=>'',
            ];
        }else{
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "type"=> 5,
                "title"=> "下单",
                "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                "link"=>'',
                "platform"=>'',
            ];
        }

        //dd($purchase_steps);
        //die("6666");

        
        #爆料修改默认值--添加帖子的时候

        //dd($data);
        $data['purchase_steps'] = json_encode($purchase_steps, JSON_UNESCAPED_UNICODE);

        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        $data['purchase_screenshots'] = json_encode($data['purchase_screenshots'], JSON_UNESCAPED_UNICODE);
        
        
        $data['product_list'] = json_encode($data['product_list'], JSON_UNESCAPED_UNICODE);
        //dd($data);
        $this->baoliao3Service->perfectInfo3($request,$data);
    }

    //爆料-完善信息
    public function perfectInfo(Request $request)
    {
        $type=$request->json("type");
        if(empty($type)){
            $type=2;
        }
        #用户id
        $user_id=$request->json("user_id");
        $avatar="";
        $nickname="";
        if(!empty($user_id) && $user_id>=1000){
           $user_info=$this->userService->update_user($user_id);
           $nickname=$user_info['nickname'];
           $avatar=$user_info['avatar'];
           
        }
        if(empty($user_id)){
            $this->error("用户Id不能为空");
        }

        $purchase=[];
        $purchase_steps=[];
        $purchase_youhuiquan=$request->json("purchase_youhuiquan");
        //dd($purchase_youhuiquan);
        $purchase_huodong=$request->json("purchase_huodong");
        $purchase_jiagou=$request->json("purchase_jiagou");
        $purchase_coudan=$request->json("purchase_coudan");

        if(!empty($purchase_youhuiquan)){
            $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
        }
        if(!empty($purchase_huodong)){
            $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
        }
        if(!empty($purchase_jiagou)){
            $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
        }
        if(!empty($purchase_coudan)){
            $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
        }
        //dd($purchase_steps);
        //佣金比例
        $commission_rate=$request->json("commission_rate");
        if(empty($commission_rate)){
            $commission_rate=0.00;
        }
        $commission_rate=$commission_rate*100;
        //数量
        $quantity=$request->json("quantity",1);
        if(empty($quantity)){
            $quantity=1;
        }
        //单价
        $unit_price=$request->json("unit_price",0);
        if(empty($unit_price)){
            $unit_price=1;
        }
        //下单价
        $final_price=$unit_price*$quantity;
        //佣金金额
        $commission_amount=$request->json("commission_amount");
        //佣金总金额
        $commission_amount_total=$commission_amount*$quantity;

        $category_id=$request->json("category_id");
        $category_name=$request->json("category_name");
        $platform=$request->json("platform");
        //dd($platform);
        $productId=$request->json("product_id");
        if($productId){
            $is_product=1;
        }

        if(!isset($this->URL_MAP[$platform])){
            $this->error("平台不存在,请联系管理员添加平台[{$platform}]");
        }
        //dd($platform);
        //测试京东
        //$platform='拼多多';
        //$productId='E9L2lYP4BSBHtvaxwfjfHwEH8luiqAiApA_JkqttchhD';
        $product_list=[];
        $url=$this->URL_MAP[$platform];
        if($url){
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform,$productId,$url);
            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }
        }
        


        $purchase_screenshots=[];
        $purchase_screenshots=$request->json("purchase_screenshots");
        $purchase_screenshots=array_filter($purchase_screenshots);
        $purchase_screenshots=array_unique($purchase_screenshots);
        //dd($purchase_screenshots);

        $image=[];
        $images=$request->json("images");
        $images=array_filter($images);
        $images=array_unique($images);

        $product_unique_id=$request->json("product_unique_id");
        if(empty($product_unique_id)&&$productId){
            $ar=explode('_',$productId);
            if(is_array($ar)){
                $product_unique_id=$ar['1'];
            }else{
                $product_unique_id=$productId;
            }

        }
        
        $data=[
            'unique_id'=>generateNum(),
            'is_product'=>$is_product,
            'purchase_steps'=>$purchase_steps,
            'title'=>$request->json("title"),
            'platform_name'=>$platform,
            'brand_name'=>$request->json("brand_name"),//品牌名称
            'start_time'=>$request->json("start_time"),
            'article_title'=>$request->json("article_title"),
            'end_time'=>$request->json("end_time"),
            'content'=>$request->json("content"),
            'cover'=>$request->json("cover"),
            'product_id'=>$productId,
            'unit_price'=>$unit_price,
            'quantity'=>$quantity,
            'final_price'=>$final_price,
            'commission_amount_total'=>$commission_amount_total,
            'images'=>$images,
            'purchase_screenshots'=>$purchase_screenshots,
            'category_id'=>$category_id,
            'category_name'=>$category_name,
            'origain_price'=>$request->json("origain_price"),
            'commission_rate'=>$commission_rate,
            'commission_amount'=>$commission_amount,//佣金金额
            'shop_id'=>$request->json("shop_id"),
            'product_unique_id'=>$product_unique_id,
            'product_list'=>$product_list,
            'type'=>$type, //2用户添加数据  3.机器人推动数据
            'publish_time'=>date("Y-m-d H:i:s"),
            'is_expired'=>2,
            'user_id'=>$user_id,
            'avatar'=>$avatar,
            'nickname'=>$nickname,

        ];


        $platform_name=$data['platform_name'];
        //活动，优惠，加购，凑单，下单
        $purchase_steps=$data['purchase_steps'];
        #组装数据
        foreach ($purchase_steps as $k=> &$v) {
            switch ($v['type']) {
                case '1':
                    $v['data-dimension122']="优惠券";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '2':
                    if(isset($v['link'])&&empty($v['link'])){
                        unset($purchase_steps[$k]);
                    }else{
                        $v['data-dimension122']="活动";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                    }
                    
                    break;
                case '3':
                    $v['data-dimension122']="加购";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                case '4':
                    $v['data-dimension122']="凑单";
                    $v['tag_text']=$v['description'];
                    $v['you_hui_tiao_zhuan_link_end']='';
                    $v['huo_dong_time']='';
                    break;
                default:
            }


        }


        //dd();
        $link="";
        if(!empty($data['product_list'])){
            $link=$data['product_list'][0]['text'];
        }
        //加购
        $purchase_steps[]=[
            "data-dimension122"=> "加购",
            "type"=>3,
            "tag_text"=> "下单{$quantity}件-{$data['title']}",
            "you_hui_tiao_zhuan_link_end"=> "",
            "huo_dong_time"=> null,
            "platform"=>$platform_name,
            "title"=> "加购",
            "description"=> "下单{$quantity}件-{$data['title']}",
            "link"=>$link,

        ];
        //$quantity=1;
        //下单
        if($quantity>1){

            $lastunitPrice = $unit_price-$commission_amount;
            //dd($commission_amount);
            //$shifu=$unit_price*$quantity;
            $lastunitPrice =_round($lastunitPrice);
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "title"=> "下单",
                "type"=> 5,
                "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                "link"=>'',
                "platform"=>'',
            ];
        }else{
            $purchase_steps[]=[
                "data-dimension122"=> "下单",
                "type"=> 5,
                "title"=> "下单",
                "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                "link"=>'',
                "platform"=>'',
            ];
        }

        //dd($purchase_steps);
        //die("6666");




        //dd($data);
        $data['purchase_steps'] = json_encode($purchase_steps, JSON_UNESCAPED_UNICODE);

        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        $data['purchase_screenshots'] = json_encode($data['purchase_screenshots'], JSON_UNESCAPED_UNICODE);
        
        
        $data['product_list'] = json_encode($data['product_list'], JSON_UNESCAPED_UNICODE);
        //dd($data);
        $this->repository->perfectInfo($request,$data);

    }

    /**
     * 识别口令链接
     * @param Request $request
     * @return JsonResponse
     */
    public function addData1(Request $request)
    {
        $data=[
            'content'=>$request->json("content"),
            'user_id'=>$request->json("user_id"),
        ];
        
        
        $this->success($this->repository->addData1($request,$data));
    }


    

  

}
